// 三种状态: pending/resolved/rejected
function myPromise(fn) {
  const that = this;
  that.state = "pending";
  that.value = null;
  that.resolveCbs = [];
  that.rejectCbs = [];
  try {
    fn(resolve, reject);
  } catch (e) {
    reject(e);
  }
  // 状态之恩能够改变一次
  function resolve(value) {
    if (that.state === "pending") {
      that.state = "resolved";
      that.value = value;
      that.resolveCbs.map((cb) => {
        cb(value);
      });
    }
  }

  function reject(value) {
    if (that.state === "pending") {
      that.state = "rejected";
      that.value = value;
      that.rejectCbs.map((cb) => {
        cb(value);
      });
    }
  }
}

myPromise.prototype.then = function (onResolve, onReject) {
  const that = this;
  return new myPromise((resolve, reject) => {
    // then 的链式调用,,要考虑到后边的then,想要执行,需要 这个 promise resolve,所以以下边方式,运行完onResolve 之后,立即执行该promise 的resolve
    // 触发后边 then 的回调
    if (that.state == "pending") {
      // that.resolveCbs.push(onResolve)
      that.resolveCbs.push((result) => {
        var x = onResolve(result);
        if (x instanceof myPromise) {
          // 获取到结果,立即resolve
          x.then(resolve, reject);
          return;
        }
        resolve(x);
      });
      that.rejectCbs.push(onReject);
    }
    // ???
    if (that.state == "resolved") {
      that.onResolve(that.value);
    }
    if (that.state == "rejected") {
      that.onReject(that.value);
    }
  });
};
new myPromise((reslove, reject) => {
  setTimeout(() => {
    reslove(1);
  }, 3000);
})
  .then((res) => {
    console.log(res);
    return new myPromise((resolve, reject) => {
      setTimeout(() => {
        resolve(10);
      }, 1000);
    });
  })
  .then((res) => {
    console.log(res);
  });
